package com.slf.engine.services.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import com.slf.engine.bo.Order;
import com.slf.engine.common.SysContants;
import com.slf.engine.exception.EngineException;
import com.slf.engine.http.HttpClientManager;
import com.slf.engine.http.HttpResponseWrapper;
import com.slf.engine.services.IEVCService;
import com.slf.engine.utils.ConnectUtil;
import com.slf.engine.utils.DateUtils;

public class EVCServiceImpl implements IEVCService {

	private static final Logger log  = Logger.getLogger(EVCServiceImpl.class);
	
	public boolean doLoginEVC()
	{
		String code = null;
		loadVerifyCode("http://221.238.6.120:8070/insms/getImgVerify2","loginCode",ConnectUtil.getInStantic());
		System.out.print("验证码存放在安装目录的images目录下，请输入验证码：");
		Scanner scanner = new Scanner(System.in);
		code = scanner.next().toUpperCase();
		
		if(code == null || code.length() != 4)
		{
			log.log(Priority.INFO, "请输入4位正确的验证码");
			return doLoginEVC();
		}
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair language2 = new NameValuePair("language2","zh");
		NameValuePair passWord = new NameValuePair("passWord",SysContants.EVC_PASSWORD);
		NameValuePair userName = new NameValuePair("userName",SysContants.EVC_LOGINNAME);
		NameValuePair verifyCode = new NameValuePair("verifyCode",code);
		NameValuePair verifyCodeKey = new NameValuePair("verifyCodeKey","$verifyCodeKey");
		NameValuePair x = new NameValuePair("x","28");
		NameValuePair y = new NameValuePair("y","15");
		params.add(language2);
		params.add(passWord);
		params.add(userName);
		params.add(verifyCode);
		params.add(verifyCodeKey);
		params.add(x);
		params.add(y);
		try {
			HttpResponseWrapper wrapper = ConnectUtil.getInStantic().execute("POST", SysContants.EVC_LOGIN_URL, SysContants.DEFAULT_CHARSET, null, null, params, null, null);
			if(wrapper.getBody() == null)
			{
				log.log(Priority.ERROR, "网页解析错误，请重试");
				return doLoginEVC();
			}
			
			String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
			if(body.indexOf("验证码错误") != -1)
			{
				log.log(Priority.INFO, "验证码校验错误，请重新输入");
				return doLoginEVC();
			}
			
			if(body.indexOf("welcome.htm") != -1)
			{
				log.log(Priority.INFO, "EVC登录成功");
				return true;
			}else{
				log.log(Priority.INFO, "EVC登录失败，请检查帐号和密码是否正确");
				return false;
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "登录网站访问错误，请重试");
			return doLoginEVC();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		}
		return false;
	}
	
	private boolean loadVerifyCode(String url,String fileName,HttpClientManager manager)
	{
		String fn = "./images/"+fileName+".jpg";
		HttpResponseWrapper wrapper = null;
		FileOutputStream output = null;
		try {
			wrapper = manager.execute("GET", url, SysContants.DEFAULT_CHARSET, null, null, null, null,null);
			File storeFile = new File(fn);  
	        output = new FileOutputStream(storeFile);  
	        //得到网络资源的字节数组,并写入文件  
	        output.write(wrapper.getBody());  
	        return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, e.getMessage());
			return loadVerifyCode(url,fileName,manager);
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, e.getMessage());
			return loadVerifyCode(url,fileName,manager);
		}finally{
			if(output != null)
			{
				try {
					output.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
				} 
			}
		}
		return false;
	}
	
	
	/**
	 * 交易线程
	 */
	public Order doPay(Order order,HttpClientManager manager,boolean isCDMA)
	{
		String OPERATOR_LOG_IDStr = null;
		String amountStr = null;
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", "http://221.238.6.120:8070/insms/dealer/en/Recharge.do?case.menuid=050116", SysContants.DEFAULT_CHARSET, null, null, null, null, null);
			if(null == wrapper.getBody())
			{
				log.log(Priority.ERROR, "进入充值页面异常");
				return doPay(order, manager,isCDMA);
			}
			String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@name='rechform']/input[@name='OPERATOR_LOG_ID']");
			if(obj != null && obj.length > 0)
			{
				TagNode node = (TagNode)obj[0];
				OPERATOR_LOG_IDStr = node.getAttributeByName("value");
			}
			
			obj = bodyNode.evaluateXPath("//form[@name='rechform']/input[@name='amount']");
			if(obj != null && obj.length > 0)
			{
				TagNode node = (TagNode)obj[0];
				amountStr = node.getAttributeByName("value");
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "进入充值页面访问异常");
			return doPay(order, manager,isCDMA);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		}
		if(OPERATOR_LOG_IDStr != null && amountStr != null)
		{
			String trans_evTypeStr = null;
			if(order.getAccount().startsWith("0"))
			{
				trans_evTypeStr = "0";
			}else{
				trans_evTypeStr = isCDMA ? "1" : "2"; //1小灵通 2CDMA
			}
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair amount = new NameValuePair("amount",amountStr);
			NameValuePair case_hidden_always = new NameValuePair("case.hidden.always","OPERATOR_LOG_ID"); 
			NameValuePair CASE_HIDDEN_ALWAYS = new NameValuePair("case.hidden.always","case.menuid");
			NameValuePair case_internal_step = new NameValuePair("case.internal.step", "2");
			NameValuePair case_menuid = new NameValuePair("case.menuid","050116");
			NameValuePair flagone = new NameValuePair("flagone","0");
			NameValuePair flagtwo = new NameValuePair("flagtwo","0");
			NameValuePair hp_no = new NameValuePair("hp_no",SysContants.EVC_LOGINNAME);
			NameValuePair minbase = new NameValuePair("minbase","1");
			NameValuePair OPERATOR_LOG_ID = new NameValuePair("OPERATOR_LOG_ID",OPERATOR_LOG_IDStr);
			NameValuePair pin_max_len = new NameValuePair("pin_max_len","30");
			NameValuePair pin_min_len = new NameValuePair("pin_min_len","4");
			NameValuePair ratejs = new NameValuePair("ratejs","0");
			NameValuePair rateofexchange = new NameValuePair("rateofexchange","1");
			NameValuePair sub = null;
			try {
				sub = new NameValuePair("sub",URLEncoder.encode("确 定", SysContants.DEFAULT_CHARSET));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			}
			NameValuePair sys_max_rech = new NameValuePair("sys_max_rech","9999999");
			NameValuePair tip_hpone =new NameValuePair("tip_hpone","");
			NameValuePair trans_evBalancetype = new NameValuePair("trans_evBalancetype","0");
			NameValuePair trans_evType = new NameValuePair("trans_evType",trans_evTypeStr);
			NameValuePair trans_money = new NameValuePair("trans_money",order.getMoney());
			NameValuePair trans_msisdn = new NameValuePair("trans_msisdn",order.getAccount());
			NameValuePair trans_pin = new NameValuePair("trans_pin", SysContants.EVC_PIN);
			NameValuePair WHERE_EV_DL_MASTER_MESSAGE = new NameValuePair("WHERE_EV_DL_MASTER_MESSAGE","0");
			
			params.add(amount);
			params.add(case_hidden_always);
			params.add(CASE_HIDDEN_ALWAYS);
			params.add(case_internal_step);
			params.add(case_menuid);
			params.add(flagone);
			params.add(flagtwo);
			params.add(hp_no);
			params.add(minbase);
			params.add(OPERATOR_LOG_ID);
			params.add(pin_max_len);
			params.add(pin_min_len);
			params.add(ratejs);
			params.add(rateofexchange);
			params.add(sub);
			params.add(sys_max_rech);
			params.add(tip_hpone);
			params.add(trans_evBalancetype);
			params.add(trans_evType);
			params.add(trans_money);
			params.add(trans_msisdn);
			params.add(trans_pin);
			params.add(WHERE_EV_DL_MASTER_MESSAGE);
			try {
				HttpResponseWrapper wrapper = manager.execute("POST", SysContants.EVC_PAY_URL, SysContants.DEFAULT_CHARSET, null, null, params, null, null);
				if(wrapper.getBody() == null)
				{
					//需要查询订单
					order.setClbz(SysContants.CZ_RUN);
					return order;
				}
				String body = new String(wrapper.getBody(),"gbk");
				if(body.indexOf("系统内部错误") != -1 || body.indexOf("系统异常") != -1)
				{
					if(!isCDMA)
					{
						return doPay(order, manager, true);
					}
					order.setClbz(SysContants.CZ_RUN);
					return order;
				}
//				log.log(Priority.INFO, "充值返回：" + body);
				if(body.indexOf("已成功充值") != -1)
				{
					order.setClbz(SysContants.CZ_SUCCESS);
					order.setCljg("充值成功");
				}else{
					order.setClbz(SysContants.CZ_RUN);
					return order;
				}
			} catch (EngineException e) {
				// TODO Auto-generated catch block
				order.setClbz(SysContants.CZ_RUN);
				return order;
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			}
		}else{
			//进入充值页面失败
//			order.setCljg("EVC充值网站访问出现异常");
//			order.setClbz(SysContants.CZ_FAILURE);
//			return order;
			return doPay(order,manager,isCDMA);
		}
		return order;
	}
	
	/**
	 * 订单查询
	 * @param order
	 * @param manager
	 * @return
	 */
	public Order doQuery(Order order, HttpClientManager manager)
	{
		String OPERATOR_LOG_IDStr = null;
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", "http://221.238.6.120:8070/insms/dealer/en/QueryOwnHisTrans.do?case.menuid=050117", SysContants.DEFAULT_CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				log.log(Priority.ERROR, "进入交易查询页面异常");
				return doQuery(order, manager);
			}
			String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
			
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@name='form']/input[@name='OPERATOR_LOG_ID']");
			if(obj != null && obj.length > 0)
			{
				TagNode node = (TagNode)obj[0];
				OPERATOR_LOG_IDStr = node.getAttributeByName("value");
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.ERROR, "进入交易查询页面异常");
			return doQuery(order, manager);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
		
		if(OPERATOR_LOG_IDStr != null)
		{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair case_hidden_always = new NameValuePair("case.hidden.always","OPERATOR_LOG_ID");
			NameValuePair CASE_HIDDEN_ALWAYS = new NameValuePair("case.hidden.always","case.menuid");
			NameValuePair case_internal_step = new NameValuePair("case.internal.step", "2");
			NameValuePair case_menuid = new NameValuePair("case.menuid","050117");
			NameValuePair dealerhpno = new NameValuePair("dealerhpno",SysContants.EVC_LOGINNAME);
			NameValuePair enddate = new NameValuePair("enddate",DateUtils.strDate("yyyy-MM-dd"));
			NameValuePair flagone = new NameValuePair("flagone","0");
			NameValuePair flagtwo = new NameValuePair("flagtwo","0");
			NameValuePair format = new NameValuePair("format","0");
			NameValuePair now = new NameValuePair("now",DateUtils.strDate("yyyyMMdd"));
			NameValuePair OPERATOR_LOG_ID = new NameValuePair("OPERATOR_LOG_ID",OPERATOR_LOG_IDStr);
			NameValuePair START_day = new NameValuePair("START_day","23");
			NameValuePair START_month = new NameValuePair("START_month","11");
			NameValuePair START_year = new NameValuePair("START_year","2004");
			NameValuePair startdate = new NameValuePair("startdate",DateUtils.yestStrDate("yyyy-MM-dd"));
			NameValuePair sub = null;
			try {
				sub = new NameValuePair("sub",URLEncoder.encode("确 定", SysContants.DEFAULT_CHARSET));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			}
			NameValuePair timeslice = new NameValuePair("timeslice","30");
			NameValuePair transtype = new NameValuePair("transtype","1");
			params.add(case_hidden_always);
			params.add(CASE_HIDDEN_ALWAYS);
			params.add(case_internal_step);
			params.add(case_menuid);
			params.add(dealerhpno);
			params.add(enddate);
			params.add(flagone);
			params.add(flagtwo);
			params.add(format);
			params.add(now);
			params.add(OPERATOR_LOG_ID);
			params.add(START_day);
			params.add(START_month);
			params.add(START_year);
			params.add(startdate);
			params.add(sub);
			params.add(timeslice);
			params.add(transtype);
			try {
				HttpResponseWrapper wrapper = manager.execute("POST", SysContants.EVC_QUERY_URL, SysContants.DEFAULT_CHARSET, null, null, params, null, null);
				if(wrapper.getBody() == null)
				{
					log.log(Priority.ERROR, "订单查询访问出现异常");
					return doQuery(order, manager);
				}
				String body = new String(wrapper.getBody(),"gbk");
				HtmlCleaner cleaner = new HtmlCleaner();
				TagNode bodyNode = cleaner.clean(body);
				Object obj[] = bodyNode.evaluateXPath("//table[@id='queryOwnHisTranstab']/tbody/tr[@class='td2']");
				if(obj != null && obj.length > 0)
				{
					for(int i = 0; i < obj.length; i++)
					{
						TagNode node = (TagNode)obj[i];
						Object tdObj[] = node.evaluateXPath("//td[@nowrap='nowrap']/text()");
						if(tdObj != null && tdObj.length > 0)
						{
							String bczsjh = ((StringBuffer)tdObj[1]).toString();
							StringBuffer yyslsh = (StringBuffer)tdObj[3];
							String czje = ((StringBuffer)tdObj[4]).toString();
							String cljg = ((StringBuffer)tdObj[6]).toString();
							int money = Integer.parseInt(czje.substring(0, czje.length()-1));
							if(order.getAccount().equals(bczsjh.trim()) && Integer.parseInt(order.getMoney()) == money)
							{
								order.setYyslsh(yyslsh.toString());
								order.setCljg(cljg);
								if(cljg.indexOf("充值成功") != -1)
								{
									order.setClbz(SysContants.CZ_SUCCESS);
								}else if(cljg.indexOf("充值失败") != -1){
									order.setClbz(SysContants.CZ_FAILURE);
								}else{
									order.setClbz(SysContants.CZ_UNKNOW);
								}
								return order;
							}
						}
					}
				}
				
			} catch (EngineException e) {
				// TODO Auto-generated catch block
				log.log(Priority.ERROR, "订单查询异常");
				return doQuery(order, manager);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			} catch (XPatherException e) {
				// TODO Auto-generated catch block
			}
		}else{
			//进入查询页面失败
			log.log(Priority.ERROR, "进入交易查询页面异常");
			return doQuery(order, manager);
		}
		return null;
	}
	
	public static void main(String args[])
	{
		IEVCService ievcService = new EVCServiceImpl();
		if(ievcService.doLoginEVC())
		{
			try {
				Thread.sleep(15000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
			}
			Order order = new Order();
			order.setAccount("13858001723");
			order.setMoney("10.0");
			ievcService.doQuery(order, ConnectUtil.getInStantic());
		}
	}
}
